package com.dxhackday.ppicker.model;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.dxhackday.ppicker.PhotoPlaybackController;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.stage.Screen;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.logging.Logger;

/**
 * User: arusakov
 * Date: 24.11.12
 * Time: 12:09
 */
public class Photo {
    private final Logger log = Logger.getLogger(Photo.class.getName());

    private final File file;

    private Image fxImage;
    private Metadata metadata;

    public Photo(File file) {
        this.file = file;
    }

    public Metadata getMetadata(){
        if (metadata == null) {
            try {
                metadata = ImageMetadataReader.readMetadata(file);
            } catch (IOException | ImageProcessingException e) {
                System.out.println("Error reading metadata: " + e.getMessage());
            }
        }
        return metadata;
    }

    public File getFile(){
        return file;
    }

    public Image getFxImage() {
        if (fxImage != null)
            return fxImage;
        String url = file.toURI().toString();
        double width = Screen.getPrimary().getVisualBounds().getWidth();
        double height = Screen.getPrimary().getVisualBounds().getHeight();
        fxImage = new Image(url, width, height, true, true, true);
        fxImage.progressProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observableValue, Number number, Number newValue) {
                if (newValue.intValue() == 1) {
                    log.info("Loaded photo '" + file.getName() + "'");
                }
            }
        });
        return fxImage;
    }

    public void disposeFxImage() {
        if (fxImage == null)
            return;
        fxImage.cancel();
        fxImage = null;
    }

    @Override
    public String toString(){
        String sum = "";
        for (Directory dir: metadata.getDirectories()){
            sum += "[" + dir + "]";
        }
        return sum + " " + file;
    }
}
